package com.fengxu.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

// bio测试
public class BioTest {

    public static void main(String[] args) throws IOException {

        // 创建线程池
        ExecutorService threadPool = new ThreadPoolExecutor(3,5,3,
                TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
                new ThreadPoolExecutor.AbortPolicy());

        // 创建服务器
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器开始监听6666端口...");

        // 监听是否有连接请求
        while (true){
            final Socket client = serverSocket.accept();
            System.out.println("服务器监听到一个请求并连接...");
            threadPool.execute(()->{
                handlerClient(client);
            });
        }

    }

    public static void handlerClient(Socket socket){
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] datas = new byte[1024];
            while (true){
                int len = inputStream.read(datas);
                if(len != -1){
                    String msg = new String(datas,0,len);
                    System.out.println(Thread.currentThread().getName()+"读取到客户端消息:"+msg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
